package u1.Server;




import u1.common.Book;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.*;
import java.util.*;


public class LocalBookCache {
    private static Map<String, ArrayList<Book>> bookType = new HashMap<>();
    private static ArrayList<Book> xhlist = new ArrayList<>();
    private static ArrayList<Book> khlist = new ArrayList<>();
    private static ArrayList<Book> trlist = new ArrayList<>();
    private static ArrayList<Book> jslist = new ArrayList<>();
    private static ArrayList<Book> yqlist = new ArrayList<>();
    private static ArrayList<Book> dslist = new ArrayList<>();
    private static ArrayList<Book> cylist = new ArrayList<>();
    private static ArrayList<Book> cslist = new ArrayList<>();
    private static ArrayList<Book> lslist = new ArrayList<>();
    private static ArrayList<Book> wxlist = new ArrayList<>();
    private static String path = "F:\\Java高级1\\novelRead\\src\\novelRead\\xnovelSave\\xsaveBook";
    ;

    static {
        readBookXml();
    }

    // 初始化小说类型列表添加进总索引

    public static void addBookType() {
        bookType.put("玄幻", xhlist);
        bookType.put("科幻", khlist);
        bookType.put("同人", trlist);
        bookType.put("军事", jslist);
        bookType.put("言情", yqlist);
        bookType.put("都市", dslist);
        bookType.put("穿越", cylist);
        bookType.put("重生", cslist);
        bookType.put("历史", lslist);
        bookType.put("无限流", wxlist);
    }

    //添加书籍进对应的类型列表

    public static void addList(Book book) {
        book.setContent("请下载");
        book.setBytes(null);
        String type = book.getType();
        if(bookType.containsKey(type)){
            ArrayList<Book> books = bookType.get(bookType);
            books.add(book);
            return;
        }

        Object[] objects = bookType.keySet().stream().filter(t -> type.contains(t)).toArray();
        for (Object i : objects) {
            ArrayList<Book> bookArrayList = bookType.get(i);
            bookArrayList.add(book);
        }
    }

    // 服务器把上传的书存入文件

    public static String saveBook(Book book) {
        book.setName(book.getAuthor() + "," + book.getTitle());
        System.out.println(book.getName());
        book.setPath(path + "/" + book.getName());
        File file = new File(book.getPath());
        BufferedOutputStream bf = null;
        try {
            bf = new BufferedOutputStream(new FileOutputStream(file));
            bf.write(book.getBytes());
            bf.flush();
            addList(book);
            saveBookXml(bookType);
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return "保存异常，可能是路径错误";
        }
    }

    // 保存索引到xml文件

    public static boolean saveBookXml(Map<String, ArrayList<Book>> bookType) throws Exception {
        XMLEncoder encoder = new XMLEncoder(new FileOutputStream("F:\\Java高级1\\novelRead\\src\\novelRead\\xnovelSave\\books.xml"));
        encoder.writeObject(bookType);
        encoder.flush();
        return true;
    }

    //读取xml中保存的索引表

    public static void readBookXml() {
        XMLDecoder decoder = null;
        try {
            decoder = new XMLDecoder(new FileInputStream("F:\\Java高级1\\novelRead\\src\\novelRead\\xnovelSave\\books.xml"));
            bookType = (Map<String, ArrayList<Book>>) decoder.readObject();
        } catch (Exception e) {
            System.out.println("不存在xml文件路径，重新初始中");
            addBookType();
        }
    }

    // 返回需要的类型列表，如果没有这个类型返回null

    public static ArrayList<Book> getList(String string) {
        Object o = bookType.keySet().stream().filter(t -> t.contains(string)).findFirst().orElse(null);
        if (o == null) {
            return null;
        }
        ArrayList<Book> bookArrayList = bookType.get(o);
        return bookArrayList;
    }

    //判断每个类型的书籍存在数量

    public static HashMap<String, Integer> existSize() {
        HashMap<String, Integer> sizeMap = new HashMap<>();
        for (String s : bookType.keySet()) {
            sizeMap.put(s, bookType.get(s).size());
        }
        return sizeMap;
    }

    // 返回完整的书籍

    public static Book download(Book book) {
        String type = book.getType();
        String s = bookType.keySet().stream().filter(t -> type.contains(t)).findFirst().orElse(null);
        if (s == null) {
            return null;
        }
        ArrayList<Book> list = bookType.get(s);
        Book newbook = list.stream().filter(str -> str.getName().equals(book.getAuthor() + "," + book.getTitle())).findFirst().orElse(null);
        newbook = getContent(newbook);
        return newbook;
    }

    // 从文件中读取小说内容

    public static Book getContent(Book book) {
        File file = new File(book.getPath());
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            StringBuffer str = new StringBuffer();
            String string = null;
            while ((string = reader.readLine()) != null) {
                str.append(string);

            }
            book.setContent(str.toString());
            return book;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //读10行，读哪行i，读哪本书book

    public static Book readOnLine(Book book, int i) {
        Book newBook = download(book);
        File file = new File(newBook.getPath());
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            StringBuffer str = new StringBuffer();
            String string = null;
            int n = (i - 1) * 10;
            int r = 0;
//            while (++r <= n) {
//                reader.readLine();
//            }
//            r=0;
            while ((string = reader.readLine()) != null && ++r <= 10) {
                str.append(string);
            }
            if (r==0){
                return null;
            }
            newBook.setContent(str.toString());
            return newBook;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Map<String, ArrayList<Book>> getBookType() {
        return bookType;
    }

    public static void setBookType(Map<String, ArrayList<Book>> bookType) {
        LocalBookCache.bookType = bookType;
    }

    public static ArrayList<Book> getXhlist() {
        return xhlist;
    }

    public static void setXhlist(ArrayList<Book> xhlist) {
        LocalBookCache.xhlist = xhlist;
    }

    public static ArrayList<Book> getKhlist() {
        return khlist;
    }

    public static void setKhlist(ArrayList<Book> khlist) {
        LocalBookCache.khlist = khlist;
    }

    public static ArrayList<Book> getTrlist() {
        return trlist;
    }

    public static void setTrlist(ArrayList<Book> trlist) {
        LocalBookCache.trlist = trlist;
    }

    public static ArrayList<Book> getJslist() {
        return jslist;
    }

    public static void setJslist(ArrayList<Book> jslist) {
        LocalBookCache.jslist = jslist;
    }

    public static ArrayList<Book> getYqlist() {
        return yqlist;
    }

    public static void setYqlist(ArrayList<Book> yqlist) {
        LocalBookCache.yqlist = yqlist;
    }

    public static ArrayList<Book> getDslist() {
        return dslist;
    }

    public static void setDslist(ArrayList<Book> dslist) {
        LocalBookCache.dslist = dslist;
    }

    public static ArrayList<Book> getCylist() {
        return cylist;
    }

    public static void setCylist(ArrayList<Book> cylist) {
        LocalBookCache.cylist = cylist;
    }

    public static ArrayList<Book> getCslist() {
        return cslist;
    }

    public static void setCslist(ArrayList<Book> cslist) {
        LocalBookCache.cslist = cslist;
    }

    public static ArrayList<Book> getLslist() {
        return lslist;
    }

    public static void setLslist(ArrayList<Book> lslist) {
        LocalBookCache.lslist = lslist;
    }

    public static ArrayList<Book> getWxlist() {
        return wxlist;
    }

    public static void setWxlist(ArrayList<Book> wxlist) {
        LocalBookCache.wxlist = wxlist;
    }

    public static String getPath() {
        return path;
    }

    public static void setPath(String path) {
        LocalBookCache.path = path;
    }
}
